<script>
	import App from './App'
	import * as msgType from '@/utils/common/messageType';
	import * as enums from '@/utils/common/enums';
	import * as wsApi from '@/utils/common/wssocket';
	import {
		getChatuserInfo,
		getPrivateMsg,
		getFriendInfo
	} from "@/api/chat.js"
	import share from "@/utils/share.js"
	export default {
		mixins: [share],
		data() {
			return {
				isInit: false, // 是否已经初始化
				isExit: false, // 是否已退出
				audioTip: null,
				reconnecting: false // 正在重连标志
			}
		},
		methods: {
			init() {
				this.isExit = false;
				// 加载数据
				this.loadStore().then(() => {
					// 初始化websocket
					this.initWebSocket();
					this.isInit = true;
				}).catch((err) => {
					console.log(err)
				})
			},
			initWebSocket() {
				let token = uni.getStorageSync("token")
				wsApi.init();
				wsApi.connect(this.define.wsURL, token);
				wsApi.onConnect(() => {
					// 重连成功提示
					if (this.reconnecting) {
						this.reconnecting = false;
						uni.showToast({
							title: "已重新连接",
							icon: 'none'
						})
					}
					// 加载离线消息
					this.pullPrivateOfflineMessage(this.chatStore.privateMsgMaxId);
				});
				wsApi.onMessage((cmd, msgInfo) => {

					if (cmd == 3) {
						// 私聊消息
						this.handlePrivateMessage(msgInfo);
					} else if (cmd == 5) {
						// 系统消息
						this.handleSystemMessage(msgInfo);
					}
				});
				wsApi.onClose((res) => {
					console.log("ws断开", res);
					// 重新连接
					this.reconnectWs();

				})
			},
			loadStore() {
				return this.userStore.loadUser().then(() => {
					const promises = [];
					promises.push(this.friendStore.loadFriend());
					promises.push(this.chatStore.loadChat());
					promises.push(this.configStore.loadConfig());
					return Promise.all(promises);
				})
			},
			unloadStore() {
				this.friendStore.clear();
				this.chatStore.clear();
				this.configStore.clear();
				this.userStore.clear();
			},
			pullPrivateOfflineMessage(minId) {
				this.chatStore.setLoadingPrivateMsg(true)
				getPrivateMsg({
					minId: minId
				}).catch(() => {
					this.chatStore.setLoadingPrivateMsg(false)
				})
			},
			handlePrivateMessage(msg) {
				// 消息加载标志
				if (msg.type == enums.MESSAGE_TYPE.LOADING) {
					this.chatStore.setLoadingPrivateMsg(JSON.parse(msg.content))
					return;
				}
				// 消息已读处理，清空已读数量
				if (msg.type == enums.MESSAGE_TYPE.READED) {
					this.chatStore.resetUnreadCount({
						type: 'PRIVATE',
						targetId: msg.recvId
					})
					return;
				}
				// 消息回执处理,改消息状态为已读
				if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
					this.chatStore.readedMessage({
						friendId: msg.sendId
					})
					return;
				}
				// 标记这条消息是不是自己发的
				let uInfo = this.xf.onlineUtils.getUserInfo();
				msg.selfSend = msg.sendId == uInfo.id;
				// 好友id
				let friendId = msg.selfSend ? msg.recvId : msg.sendId;
				this.loadFriendInfo(friendId, (friend) => {
					this.insertPrivateMessage(friend, msg);
				})
			},
			insertPrivateMessage(friend, msg) {

				let chatInfo = {
					type: 'PRIVATE',
					targetId: friend.id,
					showName: friend.nickName,
					headImage: friend.headImage
				};
				// 打开会话
				this.chatStore.openChat(chatInfo);
				// 插入消息
				this.chatStore.insertMessage(msg, chatInfo);


			},
			handleSystemMessage(msg) {
				if (msg.type == enums.MESSAGE_TYPE.USER_BANNED) {
					// 用户被封禁
					wsApi.close(3099);
					uni.showModal({
						content: '您的账号已被管理员封禁，原因:' + msg.content,
						showCancel: false,
					})
					this.exit();
				}
			},
			//获取好友信息
			loadFriendInfo(id, callback) {
				let friend = this.friendStore.findFriend(id);
				if (friend) {
					callback(friend);
				} else {
					getFriendInfo(id).then((friend) => {
						this.friendStore.addFriend(friend.data);
						callback(friend.data)
					})
				}
			},
			exit() {
				this.isExit = true;
				wsApi.close(3099);
				this.unloadStore();
			},
			reconnectWs() {
				// 已退出则不再重连
				if (this.isExit) {
					return;
				}
				// 记录标志
				this.reconnecting = true;
				// 重新加载一次个人信息，目的是为了保证网络已经正常且token有效
				this.reloadUserInfo().then((userInfo) => {
					uni.showToast({
						title: '连接已断开，尝试重新连接...',
						icon: 'none',
					})
					console.log(userInfo)
					this.userStore.setUserInfo(userInfo);
					// 重新连接
					let token = uni.getStorageSync("token")
					wsApi.reconnect(this.define.wsURL, token);
				}).catch(() => {
					// 5s后重试
					setTimeout(() => {
						this.reconnectWs();
					}, 5000)
				})
			},
			reloadUserInfo() {
				getChatuserInfo()
			},
		},
		onLaunch(options) {
		
		},
		onShow() {
			this.$mountStore();
			if (uni.getStorageSync('token')) {
				this.init()
			}
		}
	}
</script>
<style lang="scss">
	/*每个页面公共css */
	@import url('./static/icon/iconfont.css');
	@import "@/uni_modules/vk-uview-ui/index.scss";
	@import "@/assets/scss/common.scss";
	@import "@/assets/scss/public.css";
	@import "@/assets/scss/components.scss";

	page {
		color: #333;
	}
</style>